package org.example.rowing.service;

import lombok.extern.slf4j.Slf4j;
import org.example.rowing.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.List;

@Slf4j
@Service
public class LoginService {

    @Autowired
    private UserService userService;

    private String hashPassword(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if(hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public boolean validateUser(String username, String password) {
        List<User> allUsers = userService.showAllUsers();
        if(allUsers.isEmpty()) {
            // 初始化默认用户
            registerUser("admin", hashPassword("123"), true);
        }
        User user = userService.showUserByName(username);
        if(user == null) return false;
        return user.getPasswordHash().equals(hashPassword(password));
    }

    public boolean registerUser(String username, String password, boolean requireChange) {
        List<User> allUsers = userService.showAllUsers();
        if(!allUsers.isEmpty()) return false;
        User user = new User(username, password, requireChange);
        userService.saveOrUpdateUser(user);
        return true;
    }

    public boolean changePassword(String username, String oldPassword, String newPassword) {
        User user = userService.showUserByName(username);
        if (user == null || !validatePassword(user, oldPassword)) {
            return false;
        }

//        if (!validatePasswordStrength(newPassword)) {
//            return false;
//        }

        user.setPasswordHash(hashPassword(newPassword));
        user.setRequirePasswordChange(false);
        userService.saveOrUpdateUser(user);
        return true;
    }

    private boolean validatePassword(User user, String password) {
        return user.getPasswordHash().equals(hashPassword(password));
    }

    public boolean validatePasswordStrength(String password) {
        // 至少8个字符，包含大小写字母和数字
        String pattern = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}$";
        return password.matches(pattern);
    }
}
